package com.creditnet.bmc.platform.filter;


import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * XSSFilter
 * Created by bjmaozhengwei on 2018/3/31.
 */
public class XssFilter implements Filter {
    private static Logger logger = LoggerFactory.getLogger(XssFilter.class);
    /**
     * 是否过滤富文本内容
     */
    private static boolean IS_INCLUDE_RICH_TEXT = false;
    public List<String> excludes = new ArrayList<>();

    /**
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (logger.isDebugEnabled()){
            logger.debug("XSS FILTER IS [{}]","INIT");
        }
        //isIncludeRichText
        String isIncludeRichText = filterConfig.getInitParameter("isIncludeRichText");
        if (StringUtils.isNotBlank(isIncludeRichText)){
            IS_INCLUDE_RICH_TEXT = BooleanUtils.toBoolean(isIncludeRichText);
        }
        //放行规则
        String tem = filterConfig.getInitParameter("excludes");
        String[] url = tem.split(",");
        for (int i = 0; url != null && i < url.length; i++) {
            excludes.add(url[i]);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        if (logger.isDebugEnabled()){
            logger.debug("XSS FILTER IS [{}]",IS_INCLUDE_RICH_TEXT);
        }
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        if (handleExcludeURL(req,resp)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(req,IS_INCLUDE_RICH_TEXT);
        filterChain.doFilter(xssRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response){
        if (excludes == null || excludes.isEmpty()){
            return false;
        }
        String url = request.getServletPath();
        for (String pattern : excludes){
            Pattern p = Pattern.compile("^"+pattern);
            Matcher matcher = p.matcher(url);
            if (matcher.find()){
                return true;
            }
        }
        return false;
    }
}
